<template>
  <div class="create-or-edit-user">
    <el-card>
      <!-- 头部标题 -->
      <div slot="header" class="clearfix">
        <el-pageHeader
          @back="goBack"
          :content="status === 'create' ? '新建用户' : '编辑用户'"
        ></el-pageHeader>
      </div>
      <!-- 底部表单 -->
      <el-form
        :model="user"
        label-width="90px"
        label-position="left"
        ref="form"
        :rules="rules"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="user.username"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="学号"
          prop="_id"
        >
          <el-input v-model="user._id" :disabled="status === 'create' ? false : true"></el-input>
        </el-form-item>
        <el-form-item
          label="阅读组"
          prop="groups"
        >
          <el-select
            v-model="selectedGroups"
            multiple
            placeholder="请选择阅读组"
          >
            <el-option
              v-for="group in groups"
              :key="group.groupId"
              :label="group.groupName"
              :value="group.groupId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="借阅书籍">
            <el-transfer
              filterable
              :filter-method="filterMethod"
              filter-placeholder="请输入书籍编号"
              v-model="selectedBooks"
              :data="books"
              :titles="status === 'create' ? ['可借阅书籍', '已借阅书籍'] : ['已借阅书籍', '预归还书籍']"
              :button-texts="status === 'create' ? ['取消借阅', '添加借阅'] : ['取消归还', '预备归还']"
              v-loading="isLoading">
            </el-transfer>
        </el-form-item>
        <el-form-item label="借阅时间/天">
          <el-input-number v-model="user.keepTime" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="评论" v-if="status === 'edit'">
          <el-button @click.native="handleCheckComments">查看评论</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            v-if="status === 'create'"
            type="primary"
            @click="handleAdd"
          >确认添加</el-button>
          <el-button
            v-else
            type="primary"
            @click="handleEdit"
          >确认编辑</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 编辑时查看所有书评 -->
    <el-dialog :visible.sync="isCheckComments" v-if="status === 'edit'">
      <el-card>
        <div slot="header" class="clearfix main-title">《{{ user.username }}》书评</div>
        <el-table
          :data="user.comments"
          stripe
          :key="user.comments.commentId"
        >
          <el-table-column
            prop="commentId"
            label="评论编号"
          ></el-table-column>
          <el-table-column
            prop="content"
            label="内容"
          ></el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <el-button @click="handleInspest(scope)">编辑</el-button>
              <el-button
                type="danger"
                @click="handleDelete(scope)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
    <!-- 编辑时检视某条书评 -->
    <el-dialog
      :visible.sync="isInspect"
      v-if="status === 'edit'"
      :before-close="handleCancel"
    >
      <el-form
        ref="commentForm"
        :model="commentForm"
      >
        <el-form-item label="评论内容">
          <el-input type="textarea" v-model="commentForm.content"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click.native="handleCancel">取消</el-button>
          <el-button @click.native="handleCommentUpdate" type="primary">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getAllAvaiBooks } from '@/services/book'
import { getAllGroups } from '@/services/group'
import { addUser, getEditUser, editUser } from '@/services/user'
import { editComment, deleteComment } from '@/services/comment'
export default {
  name: 'CreateOrEditUser',
  props: {
    status: {
      type: String,
      default: 'create'
    },
    // 路由中的用户 id
    id: {
      type: [String, Number]
    }
  },
  data () {
    return {
      // 保存当前新建用户的信息
      user: {
        _id: null,
        username: '',
        groups: [],
        books: [],
        keepTime: 0,
        status: 0,
        permission: true,
        bookCount: 0,
        comments: []
      },
      // 学习小组列表
      groups: [],
      // 多选框暂存用户学习小组
      selectedGroups: [],
      userGroups: [],
      // 穿梭框展示数据
      books: [],
      // 穿梭框暂存用户借阅书籍
      selectedBooks: [],
      // 控制全部书评查看
      isCheckComments: false,
      // 控制某书评检视
      isInspect: false,
      // 评论表格内容
      commentForm: {},
      // 数据初始化是否完成
      isLoading: false,
      // 表单规则
      rules: {
        _id: [
          { required: true, message: '请输入唯一的学号', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      },
      // 存储当前操作的评论索引
      curCommentIndex: null,
      // 存储当前评论内容
      commentContentBeforeEdit: ''
    }
  },
  created () {
    if (this.status === 'create') {
      this.loadBooks()
    } else {
      this.loadUser()
    }
    this.loadGroups()
  },
  methods: {
    // 加载用户信息
    async loadUser () {
      const { data } = await getEditUser({
        _id: parseInt(this.id)
      })
      if (data.errcode === 0) {
        this.user = JSON.parse(data.data[0])
        this.user.groups.forEach(item => {
          this.selectedGroups.push(parseInt(item.groupId))
        })
        this.user.books.forEach(item => {
          this.books.push({
            label: item.bookName,
            key: item.bookId,
            bookId: item.bookId
          })
        })
      }
    },
    // 加载所有书籍数据
    async loadBooks () {
      this.isLoading = true
      const { data } = await getAllAvaiBooks()
      const booksArr = []
      if (data.errcode === 0) {
        data.data.forEach(item => {
          const aBook = JSON.parse(item)
          booksArr.push({
            label: aBook.bookName,
            key: aBook.bookId,
            bookId: aBook.bookId
          })
        })
        this.books = booksArr
        this.isLoading = false
      } else {
        this.$message.error('身份过期，请重新登录！')
        this.$router.push({
          name: 'login',
          query: { redirect: '/user/create' }
        })
      }
    },
    // 加载所有学习组
    async loadGroups () {
      const { data } = await getAllGroups()
      if (data.errcode === 0) {
        const groupData = []
        data.data.forEach(item => {
          const aGroup = JSON.parse(item)
          groupData.push(aGroup)
        })
        this.groups = groupData
      }
    },
    // 后退操作
    goBack () {
      this.$router.back()
    },
    // 书籍过滤,
    filterMethod (query, item) {
      if (!query) return true
      return item.bookId.toString() === query
    },
    // 查看全部评论
    handleCheckComments () {
      this.isCheckComments = true
    },
    // 查看评论内容
    handleInspest (scopeData) {
      this.isInspect = true
      this.curCommentIndex = scopeData.$index
      this.commentForm = this.user.comments[this.curCommentIndex]
      this.commentContentBeforeEdit = this.user.comments[this.curCommentIndex].content
    },
    // 修改评论
    async handleCommentUpdate () {
      const { data } = await editComment({
        _id: this.id,
        index: this.curCommentIndex,
        comment: this.commentForm
      })
      if (data.errcode === 0) {
        this.isInspect = false
        this.$message.success('修改成功')
      } else {
        this.$message.error('修改失败，请重试')
      }
    },
    // 删除评论
    handleDelete (scopeData) {
      this.curCommentIndex = scopeData.$index
      this.$confirm('确定删除评论吗？数据无法恢复！', '警告')
        .then(async () => {
          const { data } = await deleteComment({
            _id: this.id,
            index: this.curCommentIndex
          })
          if (data.errcode === 0) {
            this.$message.success('删除成功')
            this.user.comments.splice(this.curCommentIndex, 1)
          } else {
            this.$message.error('删除失败，请重试')
          }
        })
        .catch(() => {
          this.$message.info('删除取消')
        })
    },
    // 处理重置表单
    async handleReset () {
      if (this.status === 'create') {
        this.$refs.form.resetFields()
      } else {
        this.selectedGroups = []
        this.selectedBooks = []
        this.user = {}
        this.books = []
        await this.loadUser()
        await this.loadGroups()
      }
    },
    // 提交表单内容，新建角色
    handleAdd () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          this.$message.error('数据有误，请重新输入！')
        } else {
          // 重新根据选中的数据构建 user
          this.selectedGroups.forEach(item => {
            for (let i = 0; i < this.groups.length; i++) {
              if (item === this.groups[i].groupId) {
                this.user.groups.push({
                  groupId: parseInt(item),
                  groupName: this.groups[i].groupName
                })
                break
              }
            }
          })
          this.selectedBooks.forEach(item => {
            for (let i = 0; i < this.books.length; i++) {
              if (item === this.books[i].bookId) {
                this.user.books.push({
                  bookId: parseInt(item),
                  bookName: this.books[i].label
                })
                break
              }
            }
          })
          if (this.user.books.length > 0) {
            this.user.bookCount = this.user.books.length
            this.user.status = 1
          }
          this.user._id = parseInt(this.user._id)
          const { data } = await addUser(this.user)
          if (data.errcode === 0) {
            this.$message.success('添加用户成功！')
            this.$router.push({
              name: 'user'
            })
          } else if (data.errcode === -501000) {
            this.$confirm('学号已存在', '提醒')
          } else {
            this.$message.error('添加用户失败！请联系开发者！')
          }
        }
      })
    },
    // 提交表单内容，编辑角色
    handleEdit () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          this.$message.error('数据有误，请重新输入！')
        } else {
          // 重新根据选中的数据构建 user
          this.user.groups = []
          // 根据选中的学习组更新数据库
          this.selectedGroups.forEach(item => {
            for (let i = 0; i < this.groups.length; i++) {
              if (item === this.groups[i].groupId) {
                this.user.groups.push({
                  groupId: parseInt(item),
                  groupName: this.groups[i].groupName
                })
                break
              }
            }
          })
          // 反选 this.user.books 与 this.selectedBooks 的内容
          this.selectedBooks.forEach(item => {
            for (let i = 0; i < this.user.books.length;) {
              if (item === this.user.books[i].bookId) {
                this.user.books.splice(i, 1)
                continue
              }
              i++
            }
          })
          // 根据书籍数量判断其他状态
          if (this.user.books.length > 0) {
            this.user.bookCount = this.user.books.length
            this.user.status = 1
          } else {
            this.user.bookCount = 0
            this.user.status = 0
          }
          this.user._id = parseInt(this.user._id)
          const { data } = await editUser(this.user)
          if (data.errcode === 0) {
            this.$message.success('修改用户成功！')
            this.$router.push({
              name: 'user'
            })
          } else {
            this.$message.error('修改用户失败！')
          }
        }
      })
    },
    // 取消编辑评论
    handleCancel () {
      this.isInspect = false
      this.user.comments[this.curCommentIndex].content = this.commentContentBeforeEdit
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/styles/my-button.scss');
@import url('~@/styles/my-checkbox.scss');
@import url('~@/styles/my-form.scss');
</style>
